<template>
  <div class="role-detail">
    <div class="role-detail-page">
      <div class="logo-container">
        <img src="@/assets/images/LOGO1.png" alt="logo" class="logo" />
      </div>
      <div class="page-content">
        <div class="left-info-panel">
          <!-- 左侧个人信息 -->
          <div class="left-info">
            <div class="avatar-section">
              <div class="main-avatar">
                <img :src="photoList.length > 0 ? photoList[0] : ''" alt="头像" />
              </div>
            </div>

            <div class="personal-info">
              <div class="name-section">
                <div class="name-left">
                  <span class="name">{{ roleDetails['686e0c6fd9147824a38a6294'] || '子涵' }}</span>
                  <span class="gender-icon" :class="genderDisplay === '♀' ? 'female' : 'male'">
                    {{ genderDisplay }}
                  </span>
                </div>
                <!-- <span class="status-badge">已成交3单</span> -->
              </div>

              <!-- <div class="location">{{ locationText }}</div> -->

              <div class="stats-horizontal">
                <div class="stat-item">
                  <span class="stat-value"
                    >{{ Number(roleDetails['686e0f429104eb90ad4247a5']) || '168' }}cm</span
                  >
                  <span class="stat-label">身高</span>
                </div>
                <div class="stat-item">
                  <span class="stat-value"
                    >{{ Number(roleDetails['686e0f429104eb90ad4247a6']) || '47' }}kg</span
                  >
                  <span class="stat-label">体重</span>
                </div>
                <div class="stat-item">
                  <span class="stat-value">{{
                    roleDetails['688051358c409b88b8519759'] || '---'
                  }}</span>
                  <span class="stat-label">三围</span>
                </div>
                <div class="stat-item">
                  <span class="stat-value">{{ roleDetails['686e0f429104eb90ad4247a8'] }}</span>
                  <span class="stat-label">鞋码</span>
                </div>
              </div>

              <div class="divider"></div>

              <!-- 身份标签部分 -->
              <div class="identity-section">
                <h4>身份标签</h4>
                <div class="identity-tags" v-if="identityTags.length > 0">
                  <span v-for="(tag, index) in identityTags" :key="index" class="identity-tag">
                    {{ tag }}
                  </span>
                </div>
                <div v-else class="no-tags">暂无标签</div>
              </div>

              <div class="divider"></div>

              <div class="description" v-if="roleDetails['68804fc68c409b88b85196d1']">
                <h4>个人介绍</h4>
                <p>{{ roleDetails['68804fc68c409b88b85196d1'] }}</p>
              </div>
            </div>
          </div>

          <!-- 右侧照片展示区域 -->
          <div class="right-photos">
            <!-- 模卡部分 -->
            <div class="model-card">
              <p>模卡</p>
              <img :src="modelCard[0]" alt="模卡" />
            </div>
            <!-- 视频链接 -->
            <div class="video-link">
              <div class="video-link-box">
                <p>自我介绍视频链接</p>
                <a
                  :href="`/video?url=${encodeURIComponent(roleDetails['68b7b0ec6617217ad4221438'] || '')}`"
                  target="_blank"
                  class="video-link-text"
                >
                  {{ roleDetails['68b7b0ec6617217ad4221438'] }}
                </a>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, onUnmounted } from 'vue'
import { useRoute } from 'vue-router'
import { apiService } from '@/utils/api'
import { getAreaName, getProvinceAndCity } from '@/utils/areaCode'

const route = useRoute()

const props = defineProps({
  roleData: {
    type: [Object, String],
    default: () => ({}),
  },
})

const url = ref('')

const activeTab = ref('photos')
const roleDetails = ref({})

const pageWidth = ref(0)
const pageHeight = ref(0)

// 从roleDetails中获取照片列表
const photoList = computed(() => {
  if (roleDetails.value['687633c7ef700e94a0d82b59']) {
    try {
      const photoData = roleDetails.value['687633c7ef700e94a0d82b59']
      const photos = JSON.parse(photoData)

      // 检查是否是数组
      if (Array.isArray(photos) && photos.length > 0) {
        return photos
          .map((photo) => {
            // 如果是字符串，直接返回
            if (typeof photo === 'string') {
              return photo
            }
            // 如果是对象且有DownloadUrl属性
            else if (photo && photo.DownloadUrl) {
              return photo.DownloadUrl
            }
            // 其他情况
            return ''
          })
          .filter((url) => url)
      }
    } catch (error) {
      console.error('解析照片数据失败:', error, roleDetails.value['687633c7ef700e94a0d82b59'])
    }
  }
  return []
})

// 从roleDetails中获取模卡列表
const modelCard = computed(() => {
  if (roleDetails.value['688050b38c409b88b851973c']) {
    try {
      const cardData = roleDetails.value['688050b38c409b88b851973c']
      const cards = JSON.parse(cardData)

      // 检查是否是数组
      if (Array.isArray(cards) && cards.length > 0) {
        return cards
          .map((card) => {
            // 如果是字符串，直接返回
            if (typeof card === 'string') {
              return card
            }
            // 如果是对象且有DownloadUrl属性
            else if (card && card.DownloadUrl) {
              return card.DownloadUrl
            }
            // 其他情况
            return ''
          })
          .filter((url) => url)
      }
    } catch (error) {
      console.error('解析模卡数据失败:', error, roleDetails.value['688050b38c409b88b851973c'])
    }
  }
  return []
})

// 从roleDetails中获取视频列表
const mediaList = computed(() => {
  const list = []
  // 照片
  if (photoList.value.length) {
    photoList.value.forEach((url) => {
      list.push({ type: 'photo', url })
    })
  }
  // 视频
  if (roleDetails.value['688050b38c409b88b851973b']) {
    try {
      const videoData = roleDetails.value['688050b38c409b88b851973b']
      const videos = JSON.parse(videoData)
      if (Array.isArray(videos) && videos.length > 0) {
        videos.forEach((v) => {
          const url = typeof v === 'string' ? v : v.DownloadUrl
          if (url) list.push({ type: 'video', url })
        })
      }
    } catch (e) {
      console.error('解析视频数据失败:', e)
    }
  }
  return list
})

// 播放视频
const playVideo = (event) => {
  const video =
    event.target.tagName === 'VIDEO'
      ? event.target
      : event.target.closest('.video-container').querySelector('video')
  if (video.paused) {
    video.play()
    video.closest('.video-container').querySelector('.play-button-overlay').style.display = 'none'
  } else {
    video.pause()
    video.closest('.video-container').querySelector('.play-button-overlay').style.display = 'flex'
  }
}

// 视频播放结束
const onVideoEnded = (event) => {
  const overlay = event.target.closest('.video-container').querySelector('.play-button-overlay')
  overlay.style.display = 'flex'
}

// 获取地区名称
const locationText = computed(() => {
  const province = getAreaName(roleDetails.value['686e0f429104eb90ad4247a3'])

  // 检查工作范围
  const workRange = roleDetails.value['686e0f429104eb90ad4247a4']
  let rangeText = '仅本地'

  if (workRange === '470a70a3-4fc3-4c4c-bea6-3bd2a2b7556c') {
    rangeText = '全国'
  }

  return `${province} · ${rangeText}`
})

// 获取性别显示
const genderDisplay = computed(() => {
  const genderCode = roleDetails.value['686e0c6fd9147824a38a6295']
  return genderCode === '2d5e8f66-b757-4a60-b7e7-e7c2a3c716bf' ? '♀' : '♂'
})

// 处理身份标签
const identityTags = computed(() => {
  if (!roleDetails.value['68b5676f153a1d736d85931d']) {
    return []
  }

  try {
    // 尝试解析JSON
    if (typeof roleDetails.value['68b5676f153a1d736d85931d'] === 'string') {
      const parsed = JSON.parse(roleDetails.value['68b5676f153a1d736d85931d'])
      return Array.isArray(parsed) ? parsed : []
    }
    // 如果已经是数组，直接使用
    else if (Array.isArray(roleDetails.value['68b5676f153a1d736d85931d'])) {
      return roleDetails.value['68b5676f153a1d736d85931d']
    }
    return []
  } catch (error) {
    console.error('解析身份标签失败:', error)
    return []
  }
})

// 获取角色详情
const getRoleData = async () => {
  try {
    let roleId = null

    // 优先从路由参数获取角色ID
    if (route.params.rowid) {
      roleId = route.params.rowid
    }
    // 其次从props获取
    else if (typeof props.roleData === 'string') {
      roleId = props.roleData
    }

    if (roleId) {
      console.log('获取角色详情，角色ID:', roleId)

      const res = await apiService.getFilterRows({
        worksheetId: '6876257b872d9db2c7ba5297',
        filters: [
          {
            controlId: 'rowid',
            dataType: 2,
            spliceType: 1,
            filterType: 2,
            value: roleId,
          },
        ],
      })
      console.log('getRoleData 结果:', res)

      if (res && res.rows && res.rows.length > 0) {
        const filteredRows = res.rows.filter((item) => item['rowid'] === roleId)
        if (filteredRows.length > 0) {
          roleDetails.value = filteredRows[0]
          console.log('获取到的角色详情:', roleDetails.value)
        } else {
          console.warn('未找到匹配的角色ID:', roleId)
        }
      } else {
        console.warn('API返回数据为空')
      }
    } else if (props.roleData && typeof props.roleData === 'object') {
      // 如果传入的是对象，直接使用
      roleDetails.value = props.roleData
    }
  } catch (error) {
    console.error('获取角色详情失败:', error)
  }
}

// 监听路由参数变化
watch(
  () => route.params.rowid,
  (newRowId) => {
    if (newRowId) {
      getRoleData()
    }
  },
  { immediate: true },
)

const updatePageSize = () => {
  pageWidth.value = Math.max(
    document.body.scrollWidth,
    document.body.offsetWidth,
    document.documentElement.clientWidth,
    document.documentElement.scrollWidth,
    document.documentElement.offsetWidth,
  )

  pageHeight.value = Math.max(
    document.body.scrollHeight,
    document.body.offsetHeight,
    document.documentElement.clientHeight,
    document.documentElement.scrollHeight,
    document.documentElement.offsetHeight,
  )

  console.log('pageWidth', pageWidth.value)
  console.log('pageHeight', pageHeight.value)
  console.log('当前地址:', window.location.href)
  console.log('当前路径:', window.location.pathname)
  console.log(
    '完整URL:',
    `${window.location.origin}${window.location.pathname}${window.location.search}&width=${pageWidth.value}&height=${pageHeight.value}`,
  )
  url.value = `${window.location.origin}${window.location.pathname}${window.location.search}&width=${pageWidth.value}&height=${pageHeight.value}`
}

const setData = async () => {
  console.log('setData')
  const res = await apiService.submitWebhook('NjhiMmE5YTE4NmE5YWEzYjE0ZDU3YWU2', {
    url: url.value,
  })

  console.log('setData', res)
}

// 页面加载时获取数据
onMounted(async () => {
  getRoleData()
  await setData()
})
</script>

<style scoped lang="scss">
.role-detail {
  background-color: #f7f7f7;
  display: flex;
  justify-content: center;
  align-items: center;
}
.role-detail-page {
  width: 1600px;
  max-height: 100vh;
  background: #fff;
  overflow: hidden;
}

.logo-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 24px 0 0 0;
  > .logo {
    width: auto;
    height: 30px;
  }
}

.page-content {
  height: calc(100vh - 30px - 24px - 24px);
  > .left-info-panel {
    height: 98%;
    margin: 1% 4% 4% 4%;
    display: flex;
    overflow: hidden;
    background-color: #faf5f9;
    border-radius: 12px;
    border: 1px solid #fbddec;
  }
}

.left-info {
  flex: 2;
  padding: 24px;
  display: flex;
  flex-direction: column;
  gap: 16px;
  overflow-y: auto;
}

.avatar-section {
  text-align: center;
}

.main-avatar {
  width: 120px;
  height: 120px;
  border-radius: 8px;
  overflow: hidden;
  margin: 0 auto 20px;
  background: #f5f5f5;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.main-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.name-section {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
}

.name-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.name {
  font-size: 24px;
  font-weight: 700;
  color: #333;
}

.gender-icon {
  font-size: 24px;
  font-weight: 900;
}

.gender-icon.female {
  color: #ff69b4;
}

.gender-icon.male {
  color: #409eff;
}

.status-badge {
  color: #ff69b4;
  padding: 4px 12px;
  font-size: 16px;
  font-weight: 500;
}

.location {
  color: #666;
  font-size: 18px;
  margin-bottom: 24px;
}

.stats-horizontal {
  display: flex;
  justify-content: space-between;
  gap: 15px;
  margin-bottom: 30px;
  margin-top: 30px;
}

.stat-item {
  text-align: center;
}

.stat-value {
  color: black;
  display: block;
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 6px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.divider {
  height: 1px;
  background: #d5d0d3;
  margin: 15px 0;
}

.identity-section h4 {
  font-size: 12px;
  color: #767676;
  margin-bottom: 12px;
  margin-top: 60px;
}

.identity-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 15px;
}

.identity-tag {
  padding: 5px 16px;
  border: 1px solid;
  border-color: #bfbcbd;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 800;
}

.identity-tag.tag-color-0 {
  background: #f0f9ff;
  border-color: #0ea5e9;
  color: #0ea5e9;
}

.identity-tag.tag-color-1 {
  background: #fef3c7;
  border-color: #f59e0b;
  color: #f59e0b;
}

.identity-tag.tag-color-2 {
  background: #f0fdf4;
  border-color: #10b981;
  color: #10b981;
}

.identity-tag.tag-color-3 {
  background: #fce7f3;
  border-color: #ec4899;
  color: #ec4899;
}

.identity-tag.tag-color-4 {
  background: #f3e8ff;
  border-color: #8b5cf6;
  color: #8b5cf6;
}

.identity-tag.tag-color-5 {
  background: #fef2f2;
  border-color: #ef4444;
  color: #ef4444;
}

.identity-section {
  margin-bottom: 15px;
}

.description h4 {
  font-size: 12px;
  color: #767676;
  margin-bottom: 12px;
  margin-top: 30px;
}

.description p {
  font-size: 14px;
  font-weight: 800;
  line-height: 1.6;
}

.right-photos {
  flex: 5;
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
  > .model-card {
    margin: 2%;
    padding: 10px;
    height: 70%;
    min-height: 0;
    gap: 10px;
    display: flex;
    flex-direction: column;
    justify-content: start;
    align-items: center;
    background-color: #ffffff;
    border: 1px solid #e0dede;
    border-radius: 12px;
    box-sizing: border-box;
    > p {
      font-weight: 800;
      margin: 0 0 5px 0;
      flex-shrink: 0;
    }
    > img {
      width: 100%;
      height: calc(100% - 25px);
      object-fit: contain;
      max-width: 100%;
      max-height: 100%;
    }
  }

  > .video-link {
    height: 20%;
    min-height: 80px;
    max-height: 120px;
    display: flex;
    flex-direction: column;
    justify-content: start;
    align-items: center;
    padding: 0 2% 2% 2%;
    box-sizing: border-box;
    > .video-link-box {
      width: 100%;
      height: 100%;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      background-color: #ffffff;
      padding: 8px;
      border: 1px solid #e0dede;
      border-radius: 12px;
      box-sizing: border-box;
      > p {
        font-weight: 800;
        margin: 0 0 5px 0;
        font-size: 14px;
      }
      > a {
        text-decoration: none;
        color: #9ad0dc;
        margin: 5px;
        font-size: 14px;
      }
    }
  }
}

.right-header-tabs {
  display: flex;
  gap: 40px;
  padding: 24px 24px 0 24px;
  border-bottom: 1px solid #eee;
  flex-shrink: 0;
}

.right-header-tabs .tab-item {
  padding: 20px 0;
  font-size: 28px;
  color: #666;
  cursor: pointer;
  border-bottom: 2px solid transparent;
  transition: all 0.3s ease;
}

.right-header-tabs .tab-item.active {
  color: #333;
  border-bottom: none;
  position: relative;
}

.right-header-tabs .tab-item.active::after {
  content: '';
  position: absolute;
  bottom: -2px;
  left: 50%;
  transform: translateX(-50%);
  width: 2em;
  height: 3px;
  background-color: #ff69b4;
  border-radius: 2px;
}

.photos-display {
  flex: 1;
  display: grid;
  gap: 15px;
  overflow-y: auto;
  height: 100%;
  padding-right: 10px;
  align-content: start;
}

/* 媒体展示样式 */
.media-item {
  border-radius: 12px;
  overflow: hidden;
  background: #f5f5f5;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  width: 100%;
}

/* 视频容器样式 */
.video-container {
  position: relative;
  width: 100%;
  height: 100%;
  border-radius: 12px;
  overflow: hidden;
  background: #f5f5f5;
  cursor: pointer;
}

.video-player {
  width: 100%;
  height: 100%;
  object-fit: cover;
  background: #000;
  display: block;
}

.play-button-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  z-index: 1;
}

.play-button-overlay:hover {
  background: rgba(0, 0, 0, 0.5);
}

.play-icon {
  width: 60px;
  height: 60px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: #333;
  transition: all 0.3s ease;
  margin-left: 4px;
}

.play-button-overlay:hover .play-icon {
  background: rgba(255, 255, 255, 1);
  transform: scale(1.1);
}

/* 媒体数量对应的布局 */
.media-count-1 {
  aspect-ratio: 3/4;
  max-width: 400px;
  margin: 0 auto;
}

.photos-display:has(.media-count-2) {
  grid-template-columns: repeat(2, 1fr);
}

.photos-display:has(.media-count-3) {
  grid-template-columns: repeat(3, 1fr);
}

.photos-display:has(.media-count-4) {
  grid-template-columns: repeat(2, 1fr);
  grid-template-rows: repeat(2, 1fr);
}

.media-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.media-item:hover img {
  transform: scale(1.02);
}

.cards-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
  gap: 12px;
  overflow: hidden;
  height: 100%;
  max-height: calc(85vh - 220px);
  align-content: start;
}

.card-item {
  border-radius: 8px;
  overflow: hidden;
  background: #f5f5f5;
  width: 100%;
  aspect-ratio: 2/5;
}

.card-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.bottom-stats {
  background: rgba(235, 65, 150, 0.9);
  padding: 12px 16px;
  margin: 0 40px 16px 40px;
  color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 70px;
  box-sizing: border-box;
  flex-shrink: 0;
  transition: opacity 0.2s ease;
}

.bottom-stats.inactive {
  opacity: 0;
  pointer-events: none;
}

.stat-bar {
  display: flex;
  align-items: center;
  gap: 8px;
}

.stat-text {
  font-size: 24px;
}

.gender-symbol {
  font-size: 16px;
}

.stat-items {
  display: flex;
  gap: 30px;
}

.stat-items .stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
}

.stat-items .stat-item .value {
  font-size: 15px;
  font-weight: 700;
  margin-bottom: 1px;
}

.stat-items .stat-item .label {
  margin-top: 5px;
  font-size: 10px;
  opacity: 0.8;
}

.no-tags {
  color: #999;
  font-size: 16px;
  font-style: italic;
}
</style>
